package com.geek.novel.bo

import android.app.Application
import android.content.res.Resources
import android.os.Handler
import android.os.Looper
import com.geek.novel.common.Constant
import com.geek.novel.db.CustomMigration
import com.geek.novel.global.GlobalExceptionHandler
import com.geek.novel.utils.LogCatUtil
import com.geek.novel.utils.ToastUtils
import io.realm.Realm
import io.realm.RealmConfiguration
import skin.support.SkinCompatManager
import skin.support.app.SkinAppCompatViewInflater


class AppContext: Application(){
	
	companion object {
		private lateinit var mContext: AppContext

		fun getContext(): AppContext{
			return mContext
		}
		fun getResources(): Resources {
			return mContext.resources
		}

		private fun handleError(e: Throwable){
			//隐藏全局的loading弹框（TODO 这个设计还有一些问题，需要处理，比如多个请求下的弹框异常）
//			LoadingDialogUtil.getInstance().dismiss()
			LogCatUtil.e("NovelMain", e.message!!, e)
		}
		
	}

	/**创建一个全局的handler*/
	private val handler = Handler(Looper.getMainLooper())
	fun doOnMainThread(r: Runnable){
		handler.post(r)
	}

	/**主线程全局异常的处理器*/
	class MainCrashHandler: GlobalExceptionHandler.MainCrashHandler{
		override fun mainException(t: Thread?, e: Throwable?) {
			//跨线程操作时注意线程调度回主线程操作
			Handler(Looper.getMainLooper()).post {
				ToastUtils.toastLong("主线程异常: "+e!!.message)
				handleError(e)
			}
		}
	}


	/**子线程全局异常的处理器*/
	class UncaughtCrashHandler: GlobalExceptionHandler.UncaughtCrashHandler{
		override fun uncaughtException(t: Thread?, e: Throwable?) {
			//跨线程操作时注意线程调度回主线程操作
			Handler(Looper.getMainLooper()).post {
				ToastUtils.toastLong("子线程异常: "+e!!.message)
				handleError(e)
			}
		}
	}


	/**创建应用*/
	override fun onCreate() {
		super.onCreate()
		mContext = this

		//数据库相关
		Realm.init(this)
		val config = RealmConfiguration.Builder()
				.name("novel_reader.realm") //文件名
				.schemaVersion(Constant.REALM_DB_VERSION_CODE) //版本号
				.migration(CustomMigration())
				.build()
		Realm.removeDefaultConfiguration()
		Realm.setDefaultConfiguration(config)

		//全局异常捕获
		GlobalExceptionHandler.getInstance()
			.setDebugMode(true)
//			.setDebugMode(BuildConfig.DEBUG)
			.setMainCrashHandler(MainCrashHandler())
			.setUncaughtCrashHandler(UncaughtCrashHandler())
			.register()

		//换肤软件支持
		SkinCompatManager.withoutActivity(this)
				.addInflater(SkinAppCompatViewInflater()) // 基础控件换肤初始化
//				.addInflater(SkinMaterialViewInflater()) // material design 控件换肤初始化[可选]
//				.addInflater(SkinConstraintViewInflater()) // ConstraintLayout 控件换肤初始化[可选]
//				.addInflater(SkinCardViewInflater()) // CardView v7 控件换肤初始化[可选]
				.setSkinStatusBarColorEnable(false) // 关闭状态栏换肤，默认打开[可选]
				.setSkinWindowBackgroundEnable(false) // 关闭windowBackground换肤，默认打开[可选]
				.loadSkin()
		
	}

}